﻿using CCManger.Common;
using DotNetty.Buffers;
using DotNetty.Transport.Channels;
using Serilog;
using System;
using System.Text;

namespace CCManger.Client
{
    public class EchoClientHandler : ChannelHandlerAdapter
    {
        private readonly IByteBuffer initialMessage;

        public EchoClientHandler()
        {
            this.initialMessage = Unpooled.Buffer(CCManagerHelper.ClientSettings.Size);
            byte[] messageBytes = Encoding.UTF8.GetBytes("Hello world");
            this.initialMessage.WriteBytes(messageBytes);
        }

        //public override void ChannelActive(IChannelHandlerContext context) => context.WriteAndFlushAsync(this.initialMessage);
        public override void ChannelActive(IChannelHandlerContext context)
        {
            Log.Debug("我是客户端.");
            Log.Debug($"连接至服务端{context}.");

            //编码成IByteBuffer,发送至服务端
            string message = "客户端1";
            byte[] messageBytes = Encoding.UTF8.GetBytes(message);
            IByteBuffer initialMessage = Unpooled.Buffer(messageBytes.Length);
            initialMessage.WriteBytes(messageBytes);

            context.WriteAndFlushAsync(initialMessage);
        }

        public override void ChannelRead(IChannelHandlerContext context, object message)
        {
            var byteBuffer = message as IByteBuffer;
            if (byteBuffer != null)
            {
                Log.Debug("从服务端接收: " + byteBuffer.ToString(Encoding.UTF8));
            }
            context.WriteAsync(message);
        }

        public override void ChannelReadComplete(IChannelHandlerContext context) => context.Flush();

        public override void ExceptionCaught(IChannelHandlerContext context, Exception exception)
        {
            Log.Debug("Exception: " + exception);
            context.CloseAsync();
        }

        public override void HandlerAdded(IChannelHandlerContext context)
        {
            Log.Debug($"服务端{context}上线.");
            base.HandlerAdded(context);
        }

        public override void HandlerRemoved(IChannelHandlerContext context)
        {
            Log.Debug($"服务端{context}下线.");
            base.HandlerRemoved(context);
        }
    }
}